#!/usr/bin/env python
# -*- coding:utf-8 -*-
from http.server import BaseHTTPRequestHandler
import yaml
import os,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #当前程序上上上一级目录
sys.path.append(BASE_DIR) #添加环境变量
from utils.sendSocket import sendTcpData
from utils.useCmd import cmdExec,cmdExecCom
from app.dirsearch.config import config
import _thread as thread
def scan_dir(httpserver:BaseHTTPRequestHandler,params):
    '''
    扫描web敏感目录
    @params IP
    '''
    hs = httpserver
    resp = {
            'result':'success!'
            }
    hs.send_json_success(resp)
    toolPath = config_path()
    currentPath = os.path.dirname(__file__) + os.sep + "reports" + os.sep + params['name']
    cmd = "python " + toolPath +" -u " + "\'" +params['url'] + "\' -e * --plain-text-report=" + currentPath
    print("order: " + cmd)
    thread.start_new_thread(dirsearch_cmd,(cmd,))
def send_report(httpserver:BaseHTTPRequestHandler,params):
    '''
    发送扫描报告
    @params name ex:report.txt
    '''
    hs = httpserver
    resp = {
            'result':'success!'
            }
    fileName = params['name']
    report = read_report(fileName)
    if report:
        hs.send_json_success(resp)
        thread.start_new_thread(send_txt,(report,))
    else:
        hs.send_json_fail("1005","文件不存在")
def cmd_config():
    conf = config()
    ip = conf.get_ip()
    port = conf.get_port()
    return ip,port 
def config_path():
    conf = config()
    path = conf.get_path()
    return path                  
def dirsearch_cmd(cmd):
    ip,port = cmd_config()
    for c in cmdExec(cmd):
        sendTcpData(ip,port,c)
def read_report(fileName):
    filepath = os.path.dirname(__file__) + os.sep + "reports" + os.sep + fileName
    reports = []
    if os.path.exists(filepath):
        f = open(filepath,"r")
        reports = f.readlines()
    return reports
def send_txt(report:list):
    ip,port = cmd_config()
    for c in report:
        sendTcpData(ip,port,c)
